<?php

namespace app\models;

use Yii;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * 用户
 * Class User
 * @package app\models
 *
 * @property integer $id PK
 * @property integer $agent_id 代理商编号
 * @property string $username 登录用户名
 * @property string $password 登录密码
 * @property string $auth_key
 * @property integer $status 状态
 * @property integer $create_time 创建时间
 *
 * @property UserAccount $account 关联账户
 * @property Agent $agent 关联代理商
 */
class User extends ActiveRecord implements IdentityInterface
{
    const STATUS_OK = 1;
    const STATUS_STOP = 9;
    const STATUS_DELETE = 0;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password'], 'required'],
            ['agent_id','safe'],
            ['username', 'match', 'pattern' => '/^[^@]+$/', 'message' => '用户名不能包含@字符。'],
            ['username', 'unique'],
        ];
    }
    public function attributeLabels(){
        return [
            'username'=>'用户名',
            'password'=>'密码',
            'agent_id'=>'代理商',
        ];
    }
    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return User::findOne(['id' => $id]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return null;
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->auth_key === $authKey;
    }

    /**
     * 生成接口Token
     * @param $appId string 客户端AppId
     * @return string
     */
    public function generateToken($appId)
    {
        $apiClient = ApiClient::findByAppId($appId);
        return Util::makeJWT([
            'iat' => time(),
            'uid' => $this->id,
            'app' => $appId,
        ], $apiClient->app_secret);
    }

    /**
     * 验证密码
     * @param string $password 明文密码
     * @return bool
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password);
    }

    /**
     * @inheritdoc
     */
    public function afterSave($insert, $changedAttributes)
    {
        if ($insert) {
            $account = new UserAccount();
            $account->uid = $this->id;
            $account->save();
        }
        parent::afterSave($insert, $changedAttributes);
    }

    /**
     * 关联用户账户
     * @return ActiveQuery
     */
    public function getAccount()
    {
        return $this->hasOne(UserAccount::class, ['uid' => 'id']);
    }

    /**
     * 关联代理商
     * @return ActiveQuery
     */
    public function getAgent()
    {
        return $this->hasOne(Agent::class, ['id' => 'agent_id']);
    }
}
